module.exports = function rikoControl (_events) {

  events = _events instanceof Function
    ? _events
    : function () { return _events }

  function dispatch () {
    if (dispatch.debug) {
      (dispatch.debug instanceof Function ? dispatch.debug : debug)(arguments)
    }

    var event   = arguments[0]
      , args    = Array.prototype.slice.call(arguments, 1)
      , handler = dispatch.resolve(event);

    if (handler) {
      handler.apply(null, args);
    } else {
      throw new Error('riko-mvc: no event "' + event + '"')
    }
  }

  dispatch.emit = function emit () {
    var args1 = Array.prototype.slice.call(arguments, 0);
    return function () {
      var args2 = Array.prototype.slice.call(arguments, 0);
      dispatch.apply(null, args1.concat(args2))
    }
  }

  dispatch.debug = false
  dispatch.events = events
  dispatch.separator = '/'
  dispatch.resolve = function (event) {
    return event.split(dispatch.separator).reduce(function (dir, name) {
      return dir[name];
    }, dispatch.events());
  }

  function debug (event, args) {
    if (args.length > 0) {
      console.debug("dispatch", event, args);
    } else {
      console.debug("dispatch", event);
    }
  }

  return dispatch;

}
